/*
 * OpenParts
 * A dynamic-loading components framework for GWT
 * Copyright (C) 2011 Christophe Bouthier  [chris{AT}binary-gastronome{DOT}fr]
 *
 * This work is partially based on work I have done at INRIA (http://www.inria.fr) 
 * in the context of the Qualipso European Project (http://qualipso.org/),
 * The work done at INRIA is Copyright (C) 2006-2011 INRIA
 *
 * This work is distributed under the LGPL version 3
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation. See the GNU
 * Lesser General Public License in LGPL.txt for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package fr.openparts.OpenParts.test.gwt.tests;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;

import fr.openparts.OpenParts.client.OPBinding;
import fr.openparts.OpenParts.client.OPCommandCallback;
import fr.openparts.OpenParts.client.OPCommandFailureReason;
import fr.openparts.OpenParts.client.OPPartsLoader;
import fr.openparts.OpenParts.client.OPScheduler;
import fr.openparts.OpenParts.client.OPShell;

/**
 * GWT tests for the dynamic loading of parts GWT modules in OPShell.
 * 
 * @author Christophe Bouthier [chris{AT}binary-gastronome{DOT}fr]
 * @creation.date 16 December 2009
 */
public class OPShellPartLoadingTestGwt extends GWTTestCase {

    private static final String SERVICE_NAME = "dummyService_shellpartloading";

    private static final int TIMER_TIMEOUT = 5500;
    private static final int TEST_TIMEOUT = 6000;

    private OPCommandCallback callback;
    private Timer timer;

    private int onSuccessCalled = 0;
    private int onFailCalled = 0;
    private OPCommandFailureReason onFailReason;

    /**
     * Return the name of the tested GWT Module.
     * 
     * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
     */
    @Override
    public final String getModuleName() {
        return "fr.openparts.OpenParts.test.gwt.TestOpenParts";
    }

    /**
     * Called at the start of each test to set up the part.
     * 
     * @see com.google.gwt.junit.client.GWTTestCase#gwtSetUp()
     */
    @Override
    protected void gwtSetUp() throws Exception {
        super.gwtSetUp();
        OPScheduler.bind();
        OPPartsLoader.bind();
        callback = new OPCommandCallback() {
            @Override
            public void onSuccess() {
                ++onSuccessCalled;
            }

            @Override
            public void onFail(final OPCommandFailureReason reason) {
                ++onFailCalled;
                onFailReason = reason;
            }
        };
        removeScriptElement();
    }

    /**
     * Called at the end of each test to clean up the mess.
     * 
     * @see com.google.gwt.junit.client.GWTTestCase#gwtTearDown()
     */
    @Override
    protected final void gwtTearDown() throws Exception {
        super.gwtTearDown();
        onSuccessCalled = 0;
        onFailCalled = 0;
        onFailReason = null;
        unbindOPPartsLoader(OPShell.opBindingSharedInstance());
        unbindOPScheduler(OPShell.opBindingSharedInstance());
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /**
     * Test helper method building the url for a part loader. Should return a string like serviceName/serviceName.nocache.js.
     */
    public final void testHelperPartLoaderUrl() {
        assertNotNull("The part loader url shouldn't be null", OPShell.partLoaderUrlForService(SERVICE_NAME));
        assertEquals("The part loader url should have the specified format.", SERVICE_NAME + "/" + SERVICE_NAME + ".nocache.js",
                OPShell.partLoaderUrlForService(SERVICE_NAME));
    }

    /**
     * Test helper method building the url for a part loader for null service. Should raise an assertion error.
     */
    public final void testHelperPartLoaderUrlForNull() {
        if (assertionsAreEnabled()) {
            try {
                OPShell.partLoaderUrlForService(null);
                fail("OPShell should raise an assertion error when asking for loader url for a null service.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test helper method building the css id for a part loader script. Should return a string like op_loaded_script_serviceName.
     */
    public final void testHelperPartLoaderId() {
        assertNotNull("The part loader id shouldn't be null", OPShell.partLoaderIdForService(SERVICE_NAME));
        assertEquals("The part loader id should have the specified format.", "op_loaded_script_" + SERVICE_NAME, OPShell.partLoaderIdForService(SERVICE_NAME));
    }

    /**
     * Test helper method building the css id for a part loader for null service. Should raise an assertion error.
     */
    public final void testHelperPartLoaderIdForNull() {
        if (assertionsAreEnabled()) {
            try {
                OPShell.partLoaderIdForService(null);
                fail("OPShell should raise an assertion error when asking for loader id for a null service.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test checking that a part is already loaded.
     */
    public final void testIsPartAlreadyLoaded() {
        OPShell.loadPart(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);
        assertTrue("The part is already loaded", OPShell.isPartAlreadyLoaded(SERVICE_NAME));
    }

    /**
     * Test checking that a part is not already loaded.
     */
    public final void testIsPartAlreadyNotLoaded() {
        assertFalse("the part is not already loaded", OPShell.isPartAlreadyLoaded(SERVICE_NAME));
    }

    /**
     * Test checking that a part is already loaded for null service. Should raise an assertion error.
     */
    public final void testIsPartAlreadyLoadedForNull() {
        if (assertionsAreEnabled()) {
            try {
                OPShell.isPartAlreadyLoaded(null);
                fail("OPShell should raise an assertion error when asking for checking if a part is already loaded for a null service.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test loading a service in the page. Should find the corresponding script element in the page.
     */
    public final void testLoadingService() {
        OPShell.loadPart(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        final Element scriptElement = DOM.getElementById(OPShell.partLoaderIdForService(SERVICE_NAME));
        assertNotNull("There is no element with the correct id", scriptElement);
        assertEquals("The element is not a script", "script", scriptElement.getTagName().toLowerCase());
        assertEquals("The script doesn't have a javascript type", "text/javascript", scriptElement.getAttribute("type"));
        assertEquals("The script doesn't have a javascript language", "javascript", scriptElement.getAttribute("language"));
        assertEquals("The script doesn't have the correct URL", OPShell.partLoaderUrlForService(SERVICE_NAME), scriptElement.getAttribute("src"));
    }

    /**
     * Test that trying to load twice the same service load it only once really. Should find only one corresponding script element in the page.
     */
    public final void testDoubleLoadingService() {
        OPShell.loadPart(SERVICE_NAME);
        OPShell.loadPart(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        final String matchingUrl = OPShell.partLoaderUrlForService(SERVICE_NAME);
        short numberOfServiceScript = 0;
        final NodeList<com.google.gwt.dom.client.Element> scriptsElements = RootPanel.getBodyElement().getElementsByTagName("script");
        for (int i = 0; i < scriptsElements.getLength(); i++) {
            final com.google.gwt.dom.client.Element scriptElement = scriptsElements.getItem(i);
            if (matchingUrl.equals(scriptElement.getAttribute("src"))) {
                ++numberOfServiceScript;
            }
        }
        assertEquals("There should be only one script loaded", 1, numberOfServiceScript);
    }

    /**
     * Test that trying to load again the same service load it only once really. Should find only one corresponding script element in the page.
     */
    public final void testTwiceLoadingService() {
        OPShell.loadPart(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        OPShell.loadPart(SERVICE_NAME);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        final String matchingUrl = OPShell.partLoaderUrlForService(SERVICE_NAME);
        short numberOfServiceScript = 0;
        final NodeList<com.google.gwt.dom.client.Element> scriptsElements = RootPanel.getBodyElement().getElementsByTagName("script");
        for (int i = 0; i < scriptsElements.getLength(); i++) {
            final com.google.gwt.dom.client.Element scriptElement = scriptsElements.getItem(i);
            if (matchingUrl.equals(scriptElement.getAttribute("src"))) {
                ++numberOfServiceScript;
            }
        }
        assertEquals("There should be only one script loaded", 1, numberOfServiceScript);
    }

    /**
     * Test trying to load a null service. Should raise an assertion error.
     */
    public final void testLoadingNullService() {
        if (assertionsAreEnabled()) {
            try {
                OPShell.loadPart(null);
                fail("OPShell should raise an assertion error when loading a null service.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test trying to load a service without OPPartLoader binded first. Should raise an assertion error.
     */
    public final void testLoadingServiceWithoutPartLoader() {
        if (assertionsAreEnabled()) {
            unbindOPPartsLoader(OPShell.opBindingSharedInstance());
            try {
                OPShell.loadPart(SERVICE_NAME);
                fail("OPShell should raise an assertion error when trying to load a service without OPPartLoader binded first.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test loading an service. Should call the callback onSuccess() method.
     */
    public final void testLoadingExistantServiceWithCallback() {
        assertEquals("onSuccess should not have been called yet", 0, onSuccessCalled);
        assertEquals("onFail should not have been called yet", 0, onFailCalled);

        OPShell.loadPart(SERVICE_NAME, callback);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        assertEquals("onSuccess should have been called now", 1, onSuccessCalled);
        assertEquals("onFail should still not have been called", 0, onFailCalled);
    }

    /**
     * Test loading an service two times. Should call the callback onSuccess() methods 2 times.
     */
    public final void testLoadingExistantServiceWithCallback2Times() {
        assertEquals("onSuccess should not have been called yet", 0, onSuccessCalled);
        assertEquals("onFail should not have been called yet", 0, onFailCalled);

        OPShell.loadPart(SERVICE_NAME, callback);
        OPShell.notifyLoadingCompleted(SERVICE_NAME);

        assertEquals("onSuccess should have been called now", 1, onSuccessCalled);
        assertEquals("onFail should still not have been called", 0, onFailCalled);
        
        OPShell.loadPart(SERVICE_NAME, callback);

        assertEquals("onSuccess should have been called 2 times now", 2, onSuccessCalled);
        assertEquals("onFail should still not have been called", 0, onFailCalled);
    }
    
    /**
     * Test loading an service that fail. Should call the callback onFail() method, with a timeout reason.
     */
    public final void testLoadingInexistantServiceWithCallback() {
        assertEquals("onSuccess should not have been called yet", 0, onSuccessCalled);
        assertEquals("onFail should not have been called yet", 0, onFailCalled);

        OPShell.loadPart(SERVICE_NAME, callback);

        timer = new Timer() {
            public void run() {
                assertEquals("onSuccess should still not have been called", 0, onSuccessCalled);
                assertEquals("onFail should have been called now", 1, onFailCalled);
                assertNotNull("reason shouldn't be null", onFailReason);
                assertEquals("reason should be load timeout", OPCommandFailureReason.TYPE_LOAD_TIMEOUT, onFailReason.getType());
                assertNotNull("reason params shouldn't be null", onFailReason.getParams());
                assertEquals("reason service should be " + SERVICE_NAME, SERVICE_NAME,
                        onFailReason.getParams().getParamValue(OPCommandFailureReason.PARAM_SERVICE));
                finishTest();
            }
        };

        timer.schedule(TIMER_TIMEOUT);
        delayTestFinish(TEST_TIMEOUT);
    }

    /**
     * Test trying to notify a loading complete for null service. Should raise an assertion error.
     */
    public final void testNotifyLoadingCompleteWithNullService() {
        if (assertionsAreEnabled()) {
            try {
                OPShell.notifyLoadingCompleted(null);
                fail("OPShell should raise an exception when trying to notify a loading complete with a null service.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test trying to notify a loading complete without OPPartLoader binded first. Should raise an assertion error.
     */
    public final void testNotifyLoadingCompleteWithoutOPPartLoader() {
        if (assertionsAreEnabled()) {
            unbindOPPartsLoader(OPShell.opBindingSharedInstance());
            try {
                OPShell.notifyLoadingCompleted(SERVICE_NAME);
                fail("OPShell should raise an assertionError when trying to notify a loading complete without OPPartLoader binded first.");
            } catch (AssertionError e) {
                assertTrue("Error should be an AssertionError", e instanceof AssertionError);
            }
        }
    }

    /**
     * Test trying to notify a loading complete for an not loaded service. Should NOT raise an error.
     */
    public final void testNotifyLoadingCompleteOfNotLoadedService() {
        try {
            OPShell.notifyLoadingCompleted(SERVICE_NAME);
        } catch (Throwable e) {
            fail("OPShell should NOT raise an error when trying to notify a loading complete for an not loaded service");
        }
    }

    /**
     * Unbind the OPScheduler.
     */
    private final native void unbindOPScheduler(final OPBinding opbinding) /*-{
        opbinding.scheduler = null;
    }-*/;

    /**
     * Unbind the OPPartsLoader.
     */
    private final native void unbindOPPartsLoader(final OPBinding binding) /*-{
        binding.partsLoader = null;
    }-*/;

    /**
     * Remove the script element
     */
    private final void removeScriptElement() {
        final Element scriptElement = DOM.getElementById(OPShell.partLoaderIdForService(SERVICE_NAME));
        if (scriptElement == null) {
            return;
        }

        DOM.removeChild((com.google.gwt.user.client.Element) scriptElement.getParentElement(), (com.google.gwt.user.client.Element) scriptElement);
    }

    /**
     * Check if assertions are enabled.
     * 
     * @return true if assertions are enabled, false otherwise
     */
    private final boolean assertionsAreEnabled() {
        try {
            assert false;
            return false;
        } catch (AssertionError e) {
            return true;
        }
    }
}
